<template>
  <el-row class="w-100">
    <el-col :span="24">
      <el-row align="middle" style="height: 40px; background-color: rgb(225, 170, 140)">
        <el-col :span="2"></el-col>
        <el-col class="text-center" :span="20">
          <span class="fs-5 text-white">{{ friendInfo?.friendName }}</span>
        </el-col>
        <el-col class="text-center" :span="2">
          <el-button style="background: none; 
          border: none;" @click="closeWindow()" :icon="Close"></el-button>
        </el-col>
      </el-row>
      <!-- 消息框 -->
      <el-row class="p-2">
        <el-col :span="24">
          <el-scrollbar id="chat-window" ref="scrollbarRef" :height="380">
            <div ref="innerRef">
              <div class="text-center" style="color: gray;" v-if="uiData.msgList.length === 0">
                无消息
              </div>
              <div v-for="group in uiData.msgList" :key="group.timeago">
                <div class="text-center mt-2" style="color: rgb(184, 184, 184); font-size: 0.9em">
                  {{ format(group.timeago, 'zh_CN') }}
                </div>
                <div v-for="msg in group.messages" :key="msg.time">
                  <MessageLeft v-if="msg.isMy === true ? false : true">
                    <template #name>{{ msg.name }}</template>
                    <template #content>{{ msg.msg }}</template>
                  </MessageLeft>
                  <MessageRight v-else>
                    <template #name>我</template>
                    <template #content>{{ msg.msg }}</template>
                  </MessageRight>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </el-col>
      </el-row>
      <!-- 输入框 -->
      <el-row class="p-2">
        <el-col :span="24">
          <el-form @submit.prevent="uiMethods.submitMsg">
            <el-row>
              <el-col :span="24">
                <el-input v-model="uiData.msg" :autosize="{ minRows: 5, maxRows: 5 }" type="textarea" />
              </el-col>
              <el-col :span="24" class="mt-2">
                <el-row class="w-100" justify="end">
                  <el-col :span="3">
                    <el-button type="primary" :disabled="!applyChatStatus" native-type="submit">
                      发送
                    </el-button>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import MessageLeft from '@renderer/components/messageLeft.vue';
import MessageRight from '@renderer/components/messageRight.vue';
import { ElMessage, ElScrollbar } from 'element-plus';
import { nextTick, ref, defineProps } from 'vue';
import { format } from 'timeago.js';
import { useStore } from '../common/piniaStore';
import { Message_Groups, Message_Group } from '@renderer/common/type';
import { Close } from '@element-plus/icons-vue'

/**
 *friendInfo as {
    friendId: string;
    friendUserName: string;
    friendName: string;
    createTime: string;
  }
 */

const props = defineProps({
  friendInfo: {
    type: Object
  },
  applyChatStatus: {
    type: Boolean
  }
});

const uiData = ref({
  msg: '',
  msgList: [] as Message_Groups
});

const innerRef = ref<HTMLDivElement>();
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>();

const store = useStore();

// 把屏幕滚动到底部
const scrollEndWindow = () => {
  //确保dom渲染完成
  nextTick(() => {
    const chatWindow: any = document.querySelector('#chat-window');
    if (chatWindow) {
      console.log('获取到的dom高度：', chatWindow.offsetHeight);
      scrollbarRef.value!.setScrollTop(chatWindow.offsetHeight);
    }
  });
}

//监听接收器推送过来的即时消息，并处理
window.electron.ipcRenderer.on('ipc:put-socket-message', (_, friendId, friendName, time, msg) => {
  const msgListLength = uiData.value.msgList.length;
  const lastGroupIndex = uiData.value.msgList.length - 1;
  console.log('接收到对方推送的消息：', friendId, friendName, msg);
  if (props.friendInfo?.friendId === friendId) {
    if (msgListLength === 0) {
      const newGroup = createNewMessageGroup(Date.now());
      const insertedGroup = insertGroupMessage(newGroup, friendName, msg, time, false);
      uiData.value.msgList.push(insertedGroup);
      scrollEndWindow();
      return;
    }

    //判断发送的消息和最后一次比是否超过1分钟
    if (Date.now() - uiData.value.msgList[lastGroupIndex].timeago > 60000) {
      const now = Date.now();
      //大于1分钟则创建新的聊天组
      uiData.value.msgList.push({
        timeago: now,
        messages: [
          {
            name: friendName,
            msg: msg,
            time: time,
            isMy: false
          }
        ]
      });
      scrollEndWindow();
      return;
    }
    //否则在此聊天组里面添加消息
    uiData.value.msgList[lastGroupIndex].messages.push({
      name: friendName,
      msg: msg,
      time: time,
      isMy: false
    });
    scrollEndWindow();
  } else {
    //TODO通知系统有新的消息
    window.electron.ipcRenderer.send(
      'show-system-message',
      `${friendName}的消息`,
      msg
    );
  }
});

//接收格式化后的消息内容，并渲染
window.electron.ipcRenderer.on('ipc:formatted-chat-message', (_, data: Message_Groups | []) => {
  console.log('聊天窗口获取到的格式化后的消息内容：', data);
  uiData.value.msgList = data;
  scrollEndWindow();
});

const createNewMessageGroup = (timeago: number) => {
  return {
    timeago: timeago,
    messages: []
  };
}

const closeWindow = () => {
  window.electron.ipcRenderer.send('ipc:close-chat-window');
}

const insertGroupMessage = (
  group: Message_Group,
  name: string,
  msg: string,
  time: number,
  isMy: boolean
): Message_Group => {
  const temp = group;
  temp.messages.push({
    name: name,
    msg: msg,
    time: time,
    isMy: isMy
  });
  return temp;
}

const uiMethods = {
  submitMsg: () => {
    if (uiData.value.msg === '') {
      ElMessage({
        type: 'warning',
        message: '不能发送空消息',
        duration: 1000,
        showClose: true
      });
      return;
    }
    const msgListLength = uiData.value.msgList.length;
    const lastGroupIndex = uiData.value.msgList.length - 1;
    if (msgListLength === 0) {
      const newGroup = createNewMessageGroup(Date.now());
      const insertedGroup = insertGroupMessage(newGroup, '我', uiData.value.msg, Date.now(), true);
      uiData.value.msgList.push(insertedGroup);
    } else {
      //判断发送的消息和最后一次比是否超过1分钟,超过则创建新的一组消息
      if (Date.now() - uiData.value.msgList[lastGroupIndex].timeago > 60000) {
        const now = Date.now();
        const newGroup = createNewMessageGroup(now);
        const insertedGroup = insertGroupMessage(newGroup, '我', uiData.value.msg, now, true);
        uiData.value.msgList.push(insertedGroup);
      } else {
        //否则在此聊天组里面添加消息
        uiData.value.msgList[lastGroupIndex].messages.push({
          name: '我',
          msg: uiData.value.msg,
          time: Date.now(),
          isMy: true
        });
      }
    }
    // 在这里把滚动条滚到最下面
    scrollEndWindow();

    console.log('接收人：', props.friendInfo);
    // 发送消息
    store.client!.sendChatMessage(uiData.value.msg, props.friendInfo?.friendId, props.friendInfo?.friendName);
    uiData.value.msg = '';
  }
};
</script>

<style lang="scss" scoped></style>
